//
//  AttachmentViewController.swift
//  ezyform
//
//  Created by MoennigQ on 1/6/17.
//  Copyright © 2017 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import WebKit
import SnapKit
enum AttachmentType: Int{
    case PVDDetailAttachment
    case SignStatement
    case OtherLink
    case ChecklistPDF
}
class AttachmentViewController: BaseViewController{
    var attchmentType: AttachmentType = .PVDDetailAttachment
    var attachmentURL: String = ""
    var attachmentTitle: String = ""
    let wkWebView = WKWebView()
    var progBar :UIProgressView!
    
    let withoutNetworkView = DatalLoadFaildView()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
        self.loadData()
    }
    func initUI(){
        self.view.backgroundColor = UIColor(hexStr: Constant.SystemBackColor)
        self.title = attachmentTitle
        
        //process bar
        progBar = UIProgressView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 0))
        progBar.progress = 0.0
        progBar.tintColor = UIColor(rgb: 0x3BADFF)
        progBar.backgroundColor = .white
        self.wkWebView.addSubview(progBar)
        progBar.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(3)
        }
        //
        wkWebView.backgroundColor = UIColor(hexStr: Constant.SystemBackColor)
        wkWebView.navigationDelegate = self
        wkWebView.uiDelegate = self
        self.view.addSubview(wkWebView)
        wkWebView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
            make.left.right.bottom.equalToSuperview()
        }
        //
        self.withoutNetworkView.isHidden = true
        self.view.addSubview(withoutNetworkView)
        withoutNetworkView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
            make.left.right.bottom.equalToSuperview()
        }
        withoutNetworkView.retryBtn.addTarget(self, action: #selector(retryBtnClick), for: UIControl.Event.touchUpInside)
        //add observer
        self.wkWebView.addObserver(self, forKeyPath: "title", options: NSKeyValueObservingOptions.new, context: nil)
        self.wkWebView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
    }
    func loadData(){
        var request: URLRequest!
        if attchmentType == .ChecklistPDF {
            if self.attachmentURL.contains("http") {//来自服务器的
                guard let url = URL(string: self.attachmentURL) else{
                    return
                }
                request = URLRequest(url: url)
                request.setValue("iOS", forHTTPHeaderField: "X-API-MOBILE-TYPE")
                request.timeoutInterval = 10//超时时间10s
                wkWebView.load(request)
            }else{//本地
                let url = URL(fileURLWithPath: self.attachmentURL)
                wkWebView.loadFileURL(url, allowingReadAccessTo: url)
            }
        }else{
            if Connectivity.isConnectedToInternet{
                if attchmentType == .PVDDetailAttachment{
                    var resultURLString = self.attachmentURL
                    let suffixStr = (resultURLString as NSString).substring(from: resultURLString.count - 3)
                    if suffixStr.lowercased().contains("txt") || suffixStr.lowercased().contains("csv"){
                        resultURLString = "https://docs.google.com/viewer?url=" + attachmentURL
                    }
                    
                    guard let url = URL(string: resultURLString) else{
                        return
                    }
                    request = URLRequest(url: url)
                    request.setValue("iOS", forHTTPHeaderField: "X-API-MOBILE-TYPE")
                    request.timeoutInterval = 10//超时时间10s
                }else if attchmentType == .SignStatement || attchmentType == .OtherLink{
                    guard let url = URL(string: attachmentURL) else{
                        return
                    }
                    request = URLRequest(url: url)
                }
                wkWebView.load(request)
            }else{
                self.showViewAfterLoad(false)
            }
        }
        
    }
    @objc func retryBtnClick(){
        self.loadData()
    }
    func showViewAfterLoad(_ loadSuccessFlag: Bool){
        if loadSuccessFlag {
            self.wkWebView.isHidden = false
            self.withoutNetworkView.isHidden = true
            self.view.bringSubviewToFront(self.wkWebView)
        }else{
            self.wkWebView.isHidden = true
            self.withoutNetworkView.isHidden = false
            self.view.bringSubviewToFront(self.withoutNetworkView)
            
        }
    }
    func backToPreInH5(){
        //WKWebView中内部返回
        if self.wkWebView.canGoBack {
            self.wkWebView.goBack()
        }else{
            _ = self.navigationController?.popViewController(animated: false)
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progBar.alpha = 1.0
            progBar.setProgress(Float(wkWebView.estimatedProgress), animated: true)
            //Max value of process bar is 1.0
            if(self.wkWebView.estimatedProgress >= 1.0) {
                UIView.animate(withDuration: 0.3, delay: 0.1, options: UIView.AnimationOptions.curveEaseInOut, animations: { () -> Void in
                    self.progBar.alpha = 0.0
                }, completion: { (finished:Bool) -> Void in
                    self.progBar.progress = 0
                })
            }
        }else if keyPath == "title" {
            if object as? WKWebView == self.wkWebView && self.attachmentTitle == ""{
                self.title = self.wkWebView.title ?? ""
            }
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.isHidden = true
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }
    deinit {
        if self.isViewDidLoad{
            //2.remove process observer
            self.wkWebView.removeObserver(self, forKeyPath: "estimatedProgress")
            self.wkWebView.removeObserver(self, forKeyPath: "title")
        }
    }
}
extension AttachmentViewController:  WKNavigationDelegate,WKUIDelegate{
    //WKUIDelegate:create new webview when click Link in WKWebView
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView?{
        if !(navigationAction.targetFrame?.isMainFrame != nil) {
            self.wkWebView.load(navigationAction.request)
        }
        return nil
    }
    //WKNavigationDelegate
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.showViewAfterLoad(true)
    }
    //此代理方法必须实现，否则假网络时不会调用didFailProvisionalNavigation
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        decisionHandler(WKNavigationActionPolicy.allow)
    }
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        if let response = navigationResponse.response as? HTTPURLResponse, response.statusCode == 204{
            self.showViewAfterLoad(false)
            decisionHandler(WKNavigationResponsePolicy.cancel)
        }else{
            decisionHandler(WKNavigationResponsePolicy.allow)
        }
        
    }
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        self.showViewAfterLoad(false)
    }
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        self.showViewAfterLoad(false)
    }
}
